package com.demo.bookstore.servlet;

import com.demo.bookstore.bean.Book;
import com.demo.bookstore.service.BookService;
import com.demo.bookstore.service.impl.BookServiceImpl;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

/**
 * @author ddone
 * @date 2024/3/14-20:41
 */
@WebServlet("/book")
public class BookServlet extends BaseServlet{
    private final BookService bookService = new BookServiceImpl();

    public void findBookList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Book> bookList = bookService.findBookList();
        req.setAttribute("bookList",bookList);
        this.processTemplate("manager/book_manager",req,resp);
    }

    public void toAddBook(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        this.processTemplate("manager/book_add",req,resp);
    }

    public void addBook(HttpServletRequest req,HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException, IOException {
        Book book = new Book();
        BeanUtils.populate(book,req.getParameterMap());
        bookService.addBook(book);
        resp.sendRedirect(req.getContextPath()+"/book?method=findBookList");
    }
    
    public void deleteBook(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        int rows = bookService.deleteBook(id);
        resp.sendRedirect(req.getContextPath()+"/book?method=findBookList");
    }
    public void findBookById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        Book book = bookService.findBookById(id);
        req.setAttribute("updateBook",book);
        this.processTemplate("manager/book_edit",req,resp);
    }
    public void updateBook(HttpServletRequest req,HttpServletResponse resp) throws InvocationTargetException, IllegalAccessException, IOException {
        Book book = new Book();
        BeanUtils.populate(book,req.getParameterMap());
        int rows = bookService.updateBook(book);
        resp.sendRedirect(req.getContextPath()+"/book?method=findBookList");
    }
}
